import { Component, OnInit, ViewEncapsulation, Injector, OnDestroy  } from '@angular/core';
// 响应式表单
import { FormGroup } from '@angular/forms';
import {  NzModalService ,NzModalRef} from 'ng-zorro-antd/modal';
import { AddOrganizeComponent } from '../../components/add-organize/add-organize.component'
import { AddJobComponent } from '../../components/add-job/add-job.component'
// 拖拽排序表格
import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';
// 引入服务
import { DeptServiceSvr } from '../../services/dept.service'
import { Departments } from '../../domains/departments.domain'
import { JobServiceSvr } from '../../services/job.service'
import { Job } from '../../domains/job.domain'
import { EmployeeServiceSvr } from '../../services/employee.service'
import {
  AccountManagerService,
  CoreComponent,
  DataDictionary,
  DataDictionaryList,
  DataDictionaryService,
  Dynamic,
  IQuickLinkModal,
  TabView
} from 'pengesoft-ng-lib';

// 树形数据展示
export interface TreeNodeInterface {
  NodeId: number;
  Name: string;
  OnJobNum?: number;
  Leader?: string;
  level?: number;
  expand?: boolean;
  children?: TreeNodeInterface[];
  parent?: TreeNodeInterface;
} 

// 响应式表单 --新增  
interface organizeList {
  Name: string;
  ParentName: string;
  Leader?: string;
}

@Component({
  selector: 'app-organize-manage',
  templateUrl: './organize-manage.component.html',
  styleUrls: ['./organize-manage.component.less']
})
export class OrganizeManageComponent implements OnInit {

  listOfMapData: any[] = [];
  mapOfExpandedData: { [key: string]: TreeNodeInterface[] } = {};
  // 岗位的所有数据
  jobOfData:any[] = [];
  // 添加数据
  addValue: any
  // 在职人数
  onJobNum: number
  // 离职
  outJobNum: number
  // 岗位总数
  allJobNum: number
  formGroup: FormGroup;
  // 响应式表单数据 -- 增加组织
  public organizeAddOfData: organizeList[] = [];
  formAdd: any = {}

  constructor(
    public modalService:NzModalService,
    public deptSvr: DeptServiceSvr,
    public jobSvr: JobServiceSvr,
    public employSvr: EmployeeServiceSvr,
    private modalSvr: NzModalService,
  ) {}

  // 增加组织
  addOrganize(): void{
    const addModal:NzModalRef=this.modalService.create({
      nzTitle:'增加组织',
      nzContent:AddOrganizeComponent,
      nzWidth: '420px',
      nzFooter:null
    })
    addModal.afterClose.subscribe((result)=>{
      this.getAll()
    })
  }
  
  // 增加岗位
  addJob(): void{
    const addJobModal:NzModalRef=this.modalService.create({
      nzTitle:'增加岗位',
      nzContent:AddJobComponent,
      nzWidth: '420px',
      nzFooter:null
    })
    addJobModal.afterClose.subscribe((result)=>{
      this.addValue = result.form.value
      this.jobOfData = [
        ...this.jobOfData,
        {
          DeptName: result.upname,
          OnJobNum: 0,
          OffJobNum: 0,
          Job: {
            DeptId: this.addValue.ParentName[this.addValue.ParentName.length - 1],
            JobName: this.addValue.Name,
            JobNum: this.addValue.jobNum
          }
        }
      ]
      this.jobSvr.getAllJobDto().then(res => {
        this.jobOfData = this.jobOfData;
      })
    })
  }

  // 新增
  isVisible = false;
  showModal(): void {
    this.isVisible = true;
  }
  handleOk(): void {
    console.log('Button ok clicked!');
    this.isVisible = false;
  }
  handleCancel(): void {
    console.log('Button cancel clicked!');
    this.isVisible = false;
  }

  // 树形数据展示
  // 获取所有的数据
  getAll():any {
    this.deptSvr.getAllMyDepartment().then(res => {
      this.listOfMapData = [
        {
          Name: res.DeptName,
          NodeId: res.NodeId,
          Leader: res.Leader,
          OnJobNum: res.OnJobNum,
          children: res.ChildDepartment.map(items => {
            return {
              Name: items.DeptName,
              NodeId: items.NodeId,
              Leader: items.Leader,
              OnJobNum: items.OnJobNum,
              children: items.ChildDepartment.map(item => {
                return {
                  Name: item.DeptName,
                  NodeId: item.NodeId,
                  Leader: item.Leader,
                  OnJobNum: item.OnJobNum,
                  children: item.ChildDepartment.map(item => {
                    return {
                      Name: item.DeptName,
                      NodeId: item.NodeId,
                      Leader: item.Leader,
                      OnJobNum: item.OnJobNum
                    }
                  })
                }
              })
            }
          })
        }
      ]

      this.listOfMapData.forEach(item => {
        this.mapOfExpandedData[item.NodeId] = this.convertTreeToList(item);
      });

    })

  }

  collapse(array: TreeNodeInterface[], data: TreeNodeInterface, $event: boolean): void {
    if (!$event) {
      if (data.children) {
        data.children.forEach(d => {
          const target = array.find(a => a.NodeId === d.NodeId)!;
          target.expand = false;
          this.collapse(array, target, false);
        });
      } else {
        return;
      }
    }
  }

  convertTreeToList(root: TreeNodeInterface): TreeNodeInterface[] {
    const stack: TreeNodeInterface[] = [];
    const array: TreeNodeInterface[] = [];
    const hashMap = {};
    stack.push({ ...root, level: 0, expand: false });
    while (stack.length !== 0) {
      const node = stack.pop()!;
      this.visitNode(node, hashMap, array);
      if (node.children) {
        for (let i = node.children.length - 1; i >= 0; i--) {
          stack.push({ ...node.children[i], level: node.level! + 1, expand: false, parent: node });
        }
      }
    }
    return array;
  }

  visitNode(node: TreeNodeInterface, hashMap: { [key: string]: boolean }, array: TreeNodeInterface[]): void {
    if (!hashMap[node.NodeId]) {
      hashMap[node.NodeId] = true;
      array.push(node);
    }
  }

  // 拖拽排序表格
  drop(event: CdkDragDrop<string[]>): void {
    moveItemInArray(this.jobOfData, event.previousIndex, event.currentIndex);
  }

  // 获取所有岗位
  getAllJob():void {

    this.jobSvr.myGetAllJobDto().then(res => {
      this.jobOfData = res;
      // 岗位总数
      this.allJobNum = res.length
    })

    // 在职人数、离职人数
    this.employSvr.getEmpCount().then(res => {
      this.onJobNum = res.OnJobCount
      this.outJobNum = res.OffJobCount
    })

  }

  // 删除
  showDeleteConfirm(id:string,job:string,dep:string): void {
    this.modalSvr.confirm({
      nzTitle: '确定要删除本条数据吗?',
      nzContent: `<b style="color: red;">将要删除岗位名称为 ${job},所属部门为 ${dep} 的数据</b>`,
      nzOkText: '确认',
      nzOkType: 'danger',
      nzOnOk: () => {
        this.jobOfData = this.jobOfData.filter(d => d.Job.Id !== id);
        this.jobSvr.delJob(id).then(res => {
          this.getAllJob()
        })
      },
      nzCancelText: '取消',
      nzOnCancel: () => {}
    });
  }

  ngOnInit(): void {
    // 初始化
    this.getAll()
    this.getAllJob()
  }

}
